<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { request } from "../../service";

const router = useRouter();
const loading = ref(false);

/**
 * 请求用户授权获取用户信息
 */
const authorizeAndLogin = () => {
  // 在微信环境下调用微信授权接口
  // #ifdef MP-WEIXIN
  uni.getUserProfile({
    desc: "用于完善会员资料",
    success: (profileRes: any) => {
      // 存储用户信息
      uni.setStorageSync("userInfo", profileRes.userInfo);
      // 授权成功后执行登录流程
      handleWxLogin();
    },
    fail: () => {
      uni.showToast({ title: "授权失败，请允许获取用户信息", icon: "none" });
    },
  });
  // #endif
};

/**
 * 发起微信登录流程：获取 code，调用后端接口换取 token，并跳转
 */
const handleWxLogin = () => {
  if (loading.value) return;
  loading.value = true;
  // #ifdef MP-WEIXIN
  uni.login({
    provider: "weixin",
    success: async (loginRes: any) => {
      console.log("🚀 ~ success: ~ loginRes:", loginRes);
      const code = loginRes.code;
      try {
        // 使用封装的 request 方法替代 uni.request
        const data = await request<{ token: string }>({
          url: "/wxlogin",
          method: "POST",
          data: { code },
        });
        if (data.token) {
          uni.setStorageSync("token", data.token);
          // 登录成功，跳转首页
          router.replace({ path: "/pages/home/index" });
        } else {
          uni.showToast({ title: "登录失败", icon: "none" });
        }
      } catch (err: any) {
        uni.showToast({
          title: err.message || "请求失败，请稍后重试",
          icon: "none",
        });
      } finally {
        loading.value = false;
      }
    },
    fail: () => {
      uni.showToast({ title: "登录失败，请检查微信环境", icon: "none" });
      loading.value = false;
    },
  });
  // #endif
};
</script>

<template>
  <view class="login-container">
    <!-- App 名称或 Logo -->
    <view class="logo-box">
      <text class="app-name">木木搭家居</text>
    </view>
    <wd-button
      :loading="loading"
      @click="authorizeAndLogin"
      size="large"
      custom-class="custom-btn"
      >微信登录</wd-button
    >
  </view>
</template>

<style lang="scss" scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  :deep() {
    .custom-btn {
      box-shadow: 0 3px 1px -2px rgb(0 0 0 / 20%), 0 2px 2px 0 rgb(0 0 0 / 14%),
        0 1px 5px 0 rgb(0 0 0 / 12%);
      width: 90%;
    }
  }
}

.logo-box {
  display: flex;
  flex-direction: column;
  margin-bottom: 120rpx;
}

.logo {
  width: 100px;
  height: 100px;
  margin-bottom: 16px;
}

.app-name {
  color: var(--wot-color-theme);
  font-size: 24px;
  font-weight: bold;
}

.login-btn:disabled {
  opacity: 0.6;
}
</style>
